<template>
  <div style="width: 100vw;height: 100vh;" class="backbg">
    <el-container style="width: 74%;height: 615px;margin: 0 auto" >
      <el-row style="width: 100%;height: 100%;margin-top: 25px;background-color: white">
        <el-col style="width: 27%;height: 100%;">
          <el-card style="border-radius: 3%;width: 100%;height: 100%;overflow:auto">
            <div slot="header" style="font-family: 微软雅黑;">
              <span style="font-size: 18px;">当前在线用户<b>{{onlineUsers.length}}</b></span>
              <span style="font-size: 10px;padding-left: 8px;">(点击角色卡片开始聊天)</span>
            </div>
            <!--          注意这里使用v-for-->
            <div style="width: 100%;height: 100%;">
              <div key="index" style="width: 100%;height: 10%;margin-bottom: 25px;" class="el-dropdown-link"  @click="chooseChat('cluster')" :key="'cluster'">
                <el-card style="width: 100%;height: auto" shadow="hover" :style="{ backgroundColor: (selected === 'cluster') ? '#67C23A' : 'white' }">
                  <el-row style="width: 100%;height: 100%;">
                    <el-col :span="10"  style="width: 100px;position: relative;left: 22px;">
                      <span style="font-size: 20px;">公共聊天</span>
                    </el-col>
                  </el-row>
                </el-card>
              </div>
              <div v-for="user in onlineUsers" style="width: 100%;height: 10%;margin-bottom: 25px;" class="el-dropdown-link"
                   @click="chooseChat(user.username)">
                <el-card style="width: 100%;height: auto" shadow="hover" :style="{ backgroundColor: (selected === user.username) ? '#67C23A' : 'white' }">
                  <el-row style="width: 100%;height: 100%;">
                    <el-col :span="4">
                      <el-avatar :size="50" :src="require('@/assets/用户 (1).png')"></el-avatar>
                    </el-col>
                    <el-col :span="7" style="position: relative;left: 22px;top: 13px;">
                      <span>{{user.username}}</span>
                    </el-col>
                  </el-row>
                </el-card>
              </div>
            </div>

          </el-card>
        </el-col>
        <el-col style="width: 72%;height: 100%;margin-left: 3px;border-radius: 3%;border: 2px solid #DCDFE6;box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1)">
          <el-row style="width: 100%;height: 61px;">
            <div style="font-family: 微软雅黑;text-align: center;width: 100%;height: 100%;
          border-bottom: 1px solid #DCDFE6;">
              <el-image :src="require('@/assets/房屋.png')" style="width: 50px;height: 50px;position:relative;top: 6px;"></el-image>
              <span style="font-size: 30px;position: relative;bottom:1px;left: 5px;"><b>在线聊天室({{chatObjectDisplay()}})</b></span>
            </div>
          </el-row>
          <el-row style="width: 100%;height: 60%;overflow:auto;" >
            <div v-if="selected==='cluster'"><!--显示群发的-->
              <div v-for="message in messages" :key="createKey(message.source,message.target)" v-if="displayChatInfor(message)&&message.isClusterSend">
                <div v-if="isYourSelf(message.source)" style="width: 100%;height: auto;">
                  <div style="font-family: 微软雅黑;font-size: 10px;margin-left: 79%;position:relative;top: 8px;">{{message.publishTime}}</div>
                  <div style="display: flex">
                    <div class="right-message">{{message.content}}</div>
                    <div style="margin-top: 5px;margin-left: 10px;">
                      <el-avatar :size="50" :src="require('@/assets/用户 (1).png')"></el-avatar>
                    </div>
                  </div>
                </div>

                <div v-else style="width: 100%;height: auto;">
                  <div style="font-family: 微软雅黑;font-size: 10px;margin-left: 8%;position:relative;top: 8px;">{{message.publishTime}}</div>
                  <div style="display: flex">
                    <div style="margin-top: 10px;margin-left: 10px;">
                      <el-avatar :size="50" :src="require('@/assets/用户 (1).png')"></el-avatar>
                    </div>
                    <div class="left-message">{{message.content}}</div>
                  </div>
                </div>
              </div>
            </div>
            <div v-else><!--显示私聊的-->
              <div v-for="message in messages" :key="createKey(message.source,message.target)" v-if="displayChatInfor(message)&&!message.isClusterSend">
                <div v-if="isYourSelf(message.source)" style="width: 100%;height: auto;">
                  <div style="font-family: 微软雅黑;font-size: 10px;margin-left: 79%;position:relative;top: 8px;">{{message.publishTime}}</div>
                  <div style="display: flex">
                    <div class="right-message">{{message.content}}</div>
                    <div style="margin-top: 5px;margin-left: 10px;">
                      <el-avatar :size="50" :src="require('@/assets/用户 (1).png')"></el-avatar>
                    </div>
                  </div>
                </div>

                <div v-else style="width: 100%;height: auto;">
                  <div style="font-family: 微软雅黑;font-size: 10px;margin-left: 8%;position:relative;top: 8px;">{{message.publishTime}}</div>
                  <div style="display: flex">
                    <div style="margin-top: 10px;margin-left: 10px;">
                      <el-avatar :size="50" :src="require('@/assets/用户 (1).png')"></el-avatar>
                    </div>
                    <div class="left-message">{{message.content}}</div>
                  </div>
                </div>
              </div>
            </div>

          </el-row>
          <el-row style="width: 100%;height: 22%;">
            <el-input type="textarea" style="height: 100%; width: 99%;border: none;
              outline: none;position: relative;left: 1px; font-size: 21px;font-family: 微软雅黑;":rows="3"
                      v-model="textContent"></el-input><!--border: 2px solid #DCDFE6;-->
          </el-row>
          <el-row style="width: 100%;height: 8%;">
            <el-button type="primary" size="medium" style="float: right;position: relative;right: 35px;bottom: 10px;"
                       @click="sendInfor" >
              发送消息
            </el-button>
          </el-row>
        </el-col>
      </el-row>

    </el-container>
  </div>

</template>

<script>

import axios from "axios";

var socket
import moment from 'moment';
export default {
  name: "Main",
  data(){
    return {
      count:0,
      selected: null,
      //在线用户的列表
      onlineUsers:[],
      messages:[],
      textContent:'',
      socket:null
    }
  },
  methods:{

    //聊天对象显示
    chatObjectDisplay() {
      if(this.selected==null){
        return
      }
      if(this.selected==='cluster'){
        return '公共聊天'
      }
      return this.selected

    },
    //显示聊天消息
    displayChatInfor(message){
      //聊天的用户和自己
      const chatUser=this.selected //选择聊天的用户
      const yourSelf=JSON.parse(localStorage.getItem("username"))//你自己

      //先要判断是否是群发
      if(this.selected==='cluster'){
        return true
      }

      //判断自己是否正在和选择的用户聊天，如果是，返回true进行显示，否则不是，则返回false
      //如果发来的消息的目标用户是聊天的用户
      //并且发来消息的源用户是自己
      //如果我选择的用户是接收者，我是发起者，就显示
      if(chatUser==message.target&&yourSelf==message.source){
        return true
      }

      //显示别人给自己发的
      //如果我选择的聊天是发起者，我是接收者，显示消息
      if(chatUser==message.source&&yourSelf==message.target){
        return true
      }
      //否则不显示
      return false
    },

    //判断是否是自己，来排版气泡位置
    isYourSelf(username){
      const yourName=JSON.parse(localStorage.getItem("username"))
      if(username==yourName){
        console.log("是自己发的")
        return true
      }
      console.log("使他人发的")
      return false
    },
    //创建主键，利用时间戳+源用户+目标用户
    createKey(source,target){
      return source+"_"+target+"_"+new Date().getTime().toString().substring(0,5)
    },
    //发送消息
    sendInfor(){
      const source=JSON.parse(localStorage.getItem("username"))
      let target=this.selected

      //1.判断target是否为null，如果为null，则表示没有聊天对象
      if(target==null){
        this.$message.warning("请选择聊天对象再聊天！")
        return
      }

      //2.检查发送文本是否正常
      if(!this.textContent){
        this.$message.warning("请输入发送内容！")
        return
      }

      //3.检查是否是群发
      if(this.selected==='cluster'){
        var isClusterSend=true
        target=''
      }else {
        isClusterSend=false
      }


      //4.编写json对象（发送数据）
      let message={
        source:source,//发送用户
        target:target,//目标用户
        sourceUrl:JSON.parse(localStorage.getItem("url")),//发送用户的头像
        targetUrl:null,//目标用户的头像，前端不知道，后端查更新
        content:this.textContent,//发送内容
        isClusterSend:isClusterSend,//是否是群发
        publishTime:moment().format('YYYY-MM-DD HH:mm')//发送时间
      }

      //5.发送到websocket后端，调用后端的onmessage
      socket.send(JSON.stringify(message))
      //推送到当前页面的messages列表，用于个人发送消息的显示
      this.messages.push(message)
      console.log(this.messages)

      //6.清空输入文本
      this.textContent=''
    },
    //连接websocket初始化
    connectWebSocketInit(){
      let vc=this
      const username=JSON.parse(localStorage.getItem("username"))

      if(typeof (WebSocket)=="undefined"){
        console.log("你的浏览器不支持ws")
        return
      }
      console.log("你的浏览器支持ws")

      const webSocketUrl="ws://127.0.0.1:8082/chat/" + username

      //创建websocket对象，开启websocket
      socket=new WebSocket(webSocketUrl)
      vc.socket=socket

      //socket的onopen
      socket.onopen=(()=>{
        console.log(username+"已经连接上服务器")

      })

      //socket的onmessage,别人发来的消息
      socket.onmessage=function (message){
        //data数据有两种：
        //1.首次发送的用户列表信息，别人初次连接时发送的
        //2.用户发送的信息，点击聊天发送发送的
        let data=JSON.parse(message.data)
          //如果data有onlineUsers，则表示为用户列表
        if(data.onlineUsers!=null){
          vc.onlineUsers=data.onlineUsers
          return
        }
        //否则就不是,则就是用户发送的信息
        //过滤掉自己发的
        //自己给自己发，就不用发送到websocket里面了
        const yourUserName=JSON.parse(localStorage.getItem("username"))
        //是自己的话直接结束
        if(data.source==yourUserName){
          return
        }
        vc.messages.push(data)
        console.log(vc.messages)
      }

      //关闭
      socket.onclose=function (){
        console.log(username+"断开连接")
      }

    },
    chooseChat(choice){
      //如果相等，就表示点击过了，再次点击设置为null
      if (this.selected === choice) {
        this.selected = null;
      } else {
        //否则就没有点击过
        this.selected = choice;
      }
    },
  },
  mounted() {
    this.connectWebSocketInit()
  },
  beforeDestroy() {
    socket.close()
  }
}
</script>

<style scoped>
  .el-dropdown-link{
    cursor: pointer;
  }

  .right-message {
    background-color: rgb(18,183,245);
    padding: 5px;
    margin-bottom: 10px;
    width: 100px;
    word-wrap: break-word;
    /*align-self: flex-end;*/
    margin-left:78%;
    margin-top: 15px;
    font-family: 微软雅黑;
    color: #F2F6FC;
    border-radius: 10%;
    display: inline-block;
  }
  .left-message {
    background-color: #DCDFE6;
    padding: 5px;
    margin-bottom: 10px;
    max-width: 100px;
    min-width: auto;
    word-wrap: break-word;
    /*align-self: flex-end;*/
    margin-left: 12px;
    margin-top: 15px;
    font-family: 微软雅黑;
    color: #333333;
    border-radius: 10%;
    display: inline-block;
  }
  .backbg{
    background-image: url("../../assets/bg1.png");
  }
</style>